<?php
if (isset($_POST["action"]))
{
	
	$connection = mysql_connect("", "root", "hottoyonohj");
	if (!$connection)
	{
		die("Could not connect: " . mysql_error());
	}
	//else echo "connected";
	
	$select = mysql_select_db("Palserver", $connection);
	// if (!$select)
		// echo " " . mysql_error();
	//else echo "palserver selected";
	
	$action = $_POST["action"];
	if ($action == "signup")
	{
		if (isset($_POST["username"]) && isset($_POST["password"]))
		{
			$name = $_POST["username"]; $pass = $_POST["password"];
			$checker = mysql_query("SELECT 1 FROM Main WHERE username = '$_POST[username]'");
			if (mysql_num_rows($checker) == 0)
			{
				$inserter = mysql_query("INSERT INTO Main (username, password) VALUES ('$_POST[username]', '$_POST[password]')");
				if (!$inserter)
				{
					//echo " " . mysql_error();
					$output[error] = 'Sign up failed. Please try again later';
					$output[message]  = '';
				}
				else 
				{
					$output[message] = 'Sign up successfull'; //echo "inserted";
					$output[error] = '';
				}
			}
			else 
			{
				$output[error] = 'Person already exists. Try another name';
				$output[message] = '';
			}
			print (json_encode($output));//echo "Sign up success";
		}
	}
	else if ($action == "signin")
	{
		if (isset($_POST["username"]) && isset($_POST["password"]))
		{
			$name = $_POST["username"]; $pass = $_POST["password"];
			$finder = mysql_query("SELECT * FROM Main WHERE username = '$_POST[username]'");
			if (mysql_num_rows($finder) > 0)
			{
				$result = mysql_fetch_array($finder);
				if ($result[password] == $_POST["password"])
				{
					//update location data
					/*$latitude = $_POST["latitude"];
					$longitude = $_POST["longitude"];
					$onstat = (int) $_POST["onstat"];
					mysql_query("UPDATE Main SET latitude = $latitude WHERE username = '$_POST[username]'");
					mysql_query("UPDATE Main SET longitude = $longitude WHERE username = '$_POST[username]'");
					mysql_query("UPDATE Main SET onstat = $onstat WHERE username = '$_POST[username]'");*/
					$output[message] = 'Sign in successfull';
					$output[error] = '';
					//$output = array_map(utf8_encode, $result);
				}
				else
				{
					$output[message] = '';
					$output[error] = 'Invalid username or password. Please try again';
				}
			}
			else
			{
				$output[message] = '';
				$output[error] = 'Invalid username or password. Please try again';
			}
		}
		
		print (json_encode($output));
	}
	
	else if ($action == "add")
	{
		//check if person is in main table
		$friend = mysql_fetch_array(mysql_query("SELECT * FROM Main WHERE username = '$_POST[username]'"));
		if ($friend[0] == 0)
		{
			$nofriend = TRUE;
			$error = "";
		}
		else
		{
			$name = $_POST["username"] . "_ask";
			$table = mysql_query("SELECT 1 FROM $name");
			if (!$table) // if table does not exist make it
			{
				$sql = "CREATE TABLE `".$name."` (username varchar(255))";
				$creator = mysql_query($sql);
				if (!$creator)
					$error = " " . mysql_error();
			}
			$friend = mysql_query("SELECT * FROM $name WHERE username = '$_POST[mainuser]'");
			$friend = mysql_fetch_array($friend);
			if ($friend[username] != $_POST["mainuser"]) //if the friend is not yet in the table insert
			{
				$selection = mysql_query("INSERT INTO `".$name."` SELECT username FROM Main WHERE username = '$_POST[mainuser]'");
				if (!$selection) 
					$error = " " . mysql_error();
				$row = mysql_query("SELECT * FROM Main WHERE username = '$_POST[username]'");
				$row = mysql_fetch_array($row);
				$requests = $row[requests];
				if (requests < 1)
					$requests = 1;
				mysql_query("UPDATE Main SET requests = $requests WHERE username = '$_POST[username]'");
			}
		}
		
		if (is_null($error))
		{
			$output[message] = 'Add sucess';
			$output[error] = '';
		}
		else
		{
			$output[message] = '';
			if ($nofriend) $output[error] = 'This user does not exist';
			else $output[error] = 'Server is having problems. Please try again later';
		}
		print (json_encode($output));
	}
	
	//Expectation is that person's name showed up from ask list 
	else if ($action == "accept")
	{
		$name = $_POST["mainuser"] . "_friends";
		$table = mysql_query("SELECT 1 FROM $name");
		if (!$table) // if table does not exist make it
		{
			//echo "within no table";
			$sql = "CREATE TABLE `".$name."` (ID int unsigned, username varchar(255))";
			$creator = mysql_query($sql);
			if (!$creator)
				$error = " " . mysql_error();
			
		}
		$selection = mysql_query("INSERT INTO `".$name."` SELECT ID, username FROM Main WHERE username = '$_POST[username]'");
		$name = $_POST["mainuser"] . "_ask";
		$friend = mysql_query("DELETE FROM $name WHERE username = '$_POST[username]'");
		if (!$friend)
			$error = " " . mysql_error();
		
		$row = mysql_fetch_array(mysql_query("SELECT COUNT(1) FROM $name"));
		if ($row[0]== 0)
		{
			$murd = mysql_query("UPDATE Main SET requests = 0 WHERE username = '$_POST[mainuser]'");
			if (!$murd)
				$error = " " . mysql_error();
		}
		//else echo "row is not zero";
		$name = $_POST["username"] . "_friends";
		$table = mysql_query("SELECT 1 FROM $name"); 
		if (!$table) // if table does not exist make it
		{
			$sql = "CREATE TABLE `".$name."` (ID int unsigned, username varchar(255))";
			$creator = mysql_query($sql);
			if (!$creator)
				$error = " " . mysql_error();
			
		}
		$selection = mysql_query("INSERT INTO `".$name."` SELECT ID, username FROM Main WHERE username = '$_POST[mainuser]'");
		if (!selection)
			$error = " " . mysql_error();
		if (is_null($error))
		{
			$output[message] = 'Accept success';
			$output[error] = '';
		}
		else
		{
			$output[message] = '';
			$output[error] = 'Server is having problems. Please try again later';
		}
		print (json_encode($output));
	}
	
	//Expectation is that reject is called ONLY if there is a request. 
	else if ($action == "reject")
	{
		//echo "within reject";
		$name = $_POST["mainuser"] . "_ask";
		$friend = mysql_query("DELETE FROM `".$name."` WHERE username = '$_POST[username]'");
		if (!$friend)
			$error = " " . mysql_error();
		$row = mysql_fetch_array(mysql_query("SELECT COUNT(1) FROM $name"));
		if ($row[0]== 0)
		{
			$murd = mysql_query("UPDATE Main SET requests = 0 WHERE username = '$_POST[mainuser]'");
			if (!$murd)
				$error = " " . mysql_error();
		}
		//echo "done reject";
		if (is_null($error))
		{
			$output[message] = 'Reject success';
			$output[error] = '';
		}
		else
		{
			$output[message] = '';
			$output[error] = 'Server is having problems. Please try again later';
		}
		print (json_encode($output));
	}
	else if ($action == "remove")
	{
		//echo "within remove";
		$name = $_POST["mainuser"] . "_friends";
		$remove = mysql_query("DELETE FROM $name WHERE username = '$_POST[username]'");
		if (!$remove)
			$error = " " . mysql_error();
		$name = $_POST["username"] . "_friends";
		$remove = mysql_query("DELETE FROM $name WHERE username = '$_POST[mainuser]'");
		if (!$remove)
			$error = " " . mysql_error();
		if (is_null($error))
		{
			$output[message] = 'remove success';
			$output[error] = '';
		}
		else
		{
			$output[message] = '';
			$output[error] = 'Server is having problems. Please try again later';
		}
		print (json_encode($output));
		//echo "done remove";
	}
	
	else if ($action == "get")
	{
		//update location data
		$latitude = (double)$_POST["latitude"];
		$longitude = (double) $_POST["longitude"];
		$onstat = (int) $_POST["onstat"];
		if (isset($_POST["longitude"]))
		{
			mysql_query("UPDATE Main SET latitude = $latitude WHERE username = '$_POST[mainuser]'");
			mysql_query("UPDATE Main SET longitude = $longitude WHERE username = '$_POST[mainuser]'");
			mysql_query("UPDATE Main SET onstat = $onstat WHERE username = '$_POST[mainuser]'");
			mysql_query("UPDATE Main SET synctime = $_POST[synctime] WHERE username = '$_POST[mainuser]'");
			mysql_query("UPDATE Main SET status = '$_POST[status]' WHERE username = '$_POST[mainuser]'");
		}
		
		
		$people = array();
		$row = mysql_query("SELECT * FROM Main WHERE username = '$_POST[mainuser]'");
		$row = mysql_fetch_array($row);
		$requests = $row[requests];
		if ($requests == 1)
		{
			$name = $_POST["mainuser"] . "_ask";
			$table = mysql_query("SELECT * FROM $name");
			
			while($friend = mysql_fetch_array($table)) //REMEMBER THIS
			{
				$asked[] = $friend;
			}
			$people[requests] = $asked;
		}
		else $people[requests] = array(); //cant set to zero, need to make array
		
		$namer = $_POST["mainuser"] . "_friends";
		$tabler = mysql_query("SELECT COUNT(1) FROM $namer");
		$rower =  mysql_fetch_array($tabler);
		if (!$tabler || $rower[0] == 0)
			$people[friends] = array();
		else
		{
			$tabler = mysql_query("SELECT * FROM $namer");
			while($friend = mysql_fetch_array($tabler))
			{
				//$asked[] = $friend;
				$person = mysql_query("SELECT * FROM Main WHERE username = '$friend[username]'"); //could also be quotes
				//$asked[error] = " ". mysql_error();
				$person = mysql_fetch_array($person);
				$onstat = $person[onstat];
				if ($onstat != 1)
				{
					$person[latitude] = 0;
					$person[longitude] = 0;
				}
				unset($person[password]);
				$frnd[] = $person;
			}
			
			$people[friends] = $frnd;
		}
		$pstatus = mysql_fetch_array(mysql_query("SELECT * FROM Main WHERE username = '$_POST[mainuser]'"));
		$people[pstatus] = $pstatus[status];
		$people[onstat] = $pstatus[onstat];
		$people[synctime] = $pstatus[synctime];
		
		print json_encode($people);
	}
}
else echo "action not set";
?>